import {onMounted, ref} from "vue";
import type {CategoryData2} from "@/types/category";
import {getCategoryAPI} from "@/apis/category";
import {onBeforeRouteUpdate, useRoute} from "vue-router";
import type {ResponseData} from "@/types/user";

export const useCategory = () => {
  const categoryData2 = ref<CategoryData2>({} as CategoryData2)
  const route = useRoute()
  const getCategoryData = async (id: string = route.params.id as string) => {
    const res = await getCategoryAPI(id) as ResponseData<CategoryData2>
    categoryData2.value = res.result
  }
  onMounted(() => getCategoryData())
  onBeforeRouteUpdate((to) => {
    // 存在问题：使用最新的路由参数请求最新的分类数据
    return getCategoryData(to.params.id as string)
  })
  // watch(()=>route.params.id,()=>{
  //   console.log("回调函数执行了")
  // })
  return {categoryData2}
}